package com.kum.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.kum.domain.constant.MsgActionEnum;
import com.kum.domain.entity.Message;
import com.kum.netty.handler.MessageHandler;
import com.kum.netty.handler.MessageHandlerFactory;
import com.kum.utils.ChannelNoticeUtils;
import com.kum.utils.SpringUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @version V1.0
 * @Package PACKAGE_NAME
 * @auhter 枯木Kum
 * @date 2021/4/21-7:12 PM
 */
public class CustomHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ChannelGroup channels =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        Channel channel = channelHandlerContext.channel();

        Message message = null;
        MessageHandler messageHandler = null;

        try {
            message = JSON.parseObject(textWebSocketFrame.text(), Message.class);

            MessageHandlerFactory messageHandlerFactory = SpringUtils.getBean(MessageHandlerFactory.class);
            messageHandler = messageHandlerFactory.getMessageHandler(message.getType());
            if (messageHandler == null) {
                throw new JSONException();
            }
        } catch (JSONException e) {
            ChannelNoticeUtils.sendMessage(channel, MsgActionEnum.FORMAT_ERROR);
            return;
        }
        //调用消息处理类
        messageHandler.operation(channel, message);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
    }
}
